package cn.chrilwe.autocreatetable.start.manager;
/**
 *  sql解析器
 * @author chrilwe
 * 2020-8-6
 */

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import cn.chrilwe.autocreatetable.start.annotation.Entity;
import cn.chrilwe.autocreatetable.start.annotation.mysql.AutoIncrement;
import cn.chrilwe.autocreatetable.start.annotation.mysql.Column;
import cn.chrilwe.autocreatetable.start.annotation.mysql.Notnull;
import cn.chrilwe.autocreatetable.start.annotation.mysql.Table;
import cn.chrilwe.autocreatetable.start.common.Engine;
import cn.chrilwe.autocreatetable.start.statement.ColumnStatement;
import cn.chrilwe.autocreatetable.start.statement.TableStatement;

public class StatementParser {

	public TableStatement getStatement(Class<?> clazz) {
		Entity entity = clazz.getAnnotation(Entity.class);
		Table table = clazz.getAnnotation(Table.class);
		if(entity == null || table == null)
			return null;
		return doGetStatement(clazz);
	}
	
	public TableStatement doGetStatement(Class<?> clazz) {
		TableStatement ts = new TableStatement();
		
		Table table = clazz.getAnnotation(Table.class);
		String name = table.name();
		String engine = table.engine();
		if(StringUtils.isEmpty(engine))
			engine = Engine.INNODB;
		String charset = table.charset();
		if(StringUtils.isEmpty(charset))
			charset = "utf8";
		ts.setTableName(name);
		ts.setTableEngine(engine);
		ts.setTableCharset(charset);
		
		List<ColumnStatement> columnStatements = doGetColumnStatement(clazz);
		if(columnStatements != null && columnStatements.size() > 0)
			ts.setColumnStatements(columnStatements);
			
		return ts;
	}
	
	public List<ColumnStatement> doGetColumnStatement(Class<?> clazz) {
		List<ColumnStatement> l = new ArrayList<ColumnStatement>();
		Field[] declaredFields = clazz.getDeclaredFields();
		for (Field field : declaredFields) {
			ColumnStatement cs = new ColumnStatement();
			
			Column column = field.getDeclaredAnnotation(Column.class);
			if(column == null)
				continue;
			String cn = column.name();
			String type = column.type();
			int length = column.length();
			cs.setColumnName(cn);
			cs.setColumnLen(length);
			cs.setColumnType(type);
			Notnull notnull = field.getDeclaredAnnotation(Notnull.class);
			if(notnull == null)
				cs.setNull(true);
			else
				cs.setNull(false);
			AutoIncrement auto = field.getDeclaredAnnotation(AutoIncrement.class);
			if(auto == null)
				cs.setAutoIncrement(false);
			else
				cs.setAutoIncrement(true);
			l.add(cs);
		}
		return l;
	}
}
